package com.mingtu.guards.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.TileOverlay;
import com.amap.api.maps.model.TileOverlayOptions;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.bean.UserInfoBean;
import com.mingtu.common.callback.ResultCallback;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.guards.R;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.MenuDeviceBean;
import com.mingtu.guards.utils.TileUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.common.utils.MyUtills.getBounds;
import static com.mingtu.guards.utils.MyConstant.MAP_FACTORY_PADDING;
import static com.mingtu.guards.utils.MyConstant.MAP_INDEX;
import static com.mingtu.guards.utils.MyConstant.MAX_ZOOM;

public class OnlinePeopleMapActivity extends MyBaseActivity {
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.iv_location)
    ImageView ivLocation;
    @BindView(R.id.iv_switch)
    ImageView ivSwitch;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    private AMap aMap;
    private List<Marker> markerList = new ArrayList<>();
    private LatLng location;
    private View infoWindow;
    private int position;
    private TileOverlayOptions tileOverlayOptions;
    private TileOverlay tileOverlay;
    private boolean isSwitch = true;
    private ImmersionBar immersionBar;

    private final int UPDATE_DEVICE_DATA = 100;
    private static int delay = 0;
    private static int period = 10 * 1000;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_DEVICE_DATA:
                    getDeviceData();
                    break;
                default:
                    break;
            }
        }
    };
    private Timer mTimer;
    private TimerTask mTimerTask;
    private List<Marker> deviceMarker;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_online_people_map;
    }

    @Override
    protected void initView() {
        hideHeadView();
        StatusBarUtil.addStatusBarHeight(statusBarView);
        //沉侵式状态栏
        immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
        immersionBar.navigationBarDarkIcon(false);
        immersionBar.init();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getData() {
        position = getIntent().getIntExtra("position", 404);
    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                startGetDeviceData();

            }
        });
        String longitude = SPStaticUtils.getString(SPTools.lng);
        String latitude = SPStaticUtils.getString(SPTools.lat);
        if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) {
            location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
            //添加Marker
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(location)
                    .icon(BitmapDescriptorFactory.fromResource(com.mingtu.home.R.mipmap.sb_icon_wz));
            Marker marker = aMap.addMarker(markerOptions);
            markerList.add(marker);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }

        //自定义瓦片
        tileOverlayOptions = TileUtils.getTileOverlayOptions();
        tileOverlay = aMap.addTileOverlay(tileOverlayOptions);
    }

    @OnClick({R.id.iv_location, R.id.iv_switch, R.id.iv_back})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                ActivityUtil.removeActivity(this);
                break;
            case R.id.iv_location:
                if (location != null) {
                    aMap.animateCamera(CameraUpdateFactory.changeLatLng(location));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));
                }
                break;
            case R.id.iv_switch:
                if (isSwitch) {
                    isSwitch = false;
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                    tileOverlay.setVisible(false);
                    immersionBar.statusBarDarkFont(true);
                    immersionBar.init();
                } else {
                    isSwitch = true;
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                    tileOverlay.setVisible(true);
                    immersionBar.statusBarDarkFont(false);
                    immersionBar.init();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (aMap != null) {
            mapView.onDestroy();
        }

        if (markerList.size() > 0) {
            for (Marker marker : markerList) {
                marker.remove();
            }
            markerList.clear();
        }

        stopGetDeviceData();

        super.onDestroy();
    }


    public void startGetDeviceData() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    sendMessage(UPDATE_DEVICE_DATA);
                }
            };
        }
        if (mTimer != null && mTimerTask != null) {
            mTimer.schedule(mTimerTask, delay, period);
        }

    }

    public void sendMessage(int id) {
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    public void stopGetDeviceData() {

        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }

        if (deviceMarker != null) {
            if (deviceMarker.size() > 0) {
                for (Marker marker : deviceMarker) {
                    marker.remove();
                }
            }
            deviceMarker.clear();
        }

    }

    /**
     * 在线人员信息
     */
    private void getDeviceData() {
        //每次创建之前需要把设备图标给清除下
        if (deviceMarker != null) {
//            MyLogUtil.e("test", "deviceMarker==" + deviceMarker.size());
            if (deviceMarker.size() > 0) {
                for (Marker marker : deviceMarker) {
                    marker.remove();
                }
                deviceMarker.clear();
            }
        }

        OkGo.<String>post(Constant.getInstance().POST_DEVICE_LIST)
                .tag(this)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                MenuDeviceBean menuDeviceBean = new MenuDeviceBean();
                                menuDeviceBean = gson.fromJson(result, MenuDeviceBean.class);

                                List<MenuDeviceBean.DataBean.OfflineListBean> offlineListBeans = menuDeviceBean.getData().getOfflineList();
                                List<MenuDeviceBean.DataBean.OnlineListBean> onlineListBeans = menuDeviceBean.getData().getOnlineList();
                                List<LatLng> latLngs = new ArrayList<>();
                                List<String> nameList = new ArrayList<>();
                                deviceMarker = new CopyOnWriteArrayList<>();
                                //暂时隐藏离线的设备
//                                for (int i = 0; i < offlineListBeans.size(); i++) {
//                                    MenuDeviceBean.DataBean.OfflineListBean offlineListBean = offlineListBeans.get(i);
//                                    try {
//                                        String lat = offlineListBean.getLat();
//                                        String lng = offlineListBean.getLng();
//                                        String name = offlineListBean.getName();
//
//                                        if (!StringUtils.isEmpty(lat) && !StringUtils.isEmpty(lng)) {
//                                            LatLng latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
//                                            latLngs.add(latLng);
//                                            nameList.add(name);
//                                        }
//
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//
//                                }

                                for (int i = 0; i < onlineListBeans.size(); i++) {
                                    MenuDeviceBean.DataBean.OnlineListBean onlineListBean = onlineListBeans.get(i);
                                    try {
                                        String lat = onlineListBean.getLat();
                                        String lng = onlineListBean.getLng();
                                        String name = onlineListBean.getName();
                                        String deviceUserId = onlineListBean.getUserId() + "";

                                        String userId = SPStaticUtils.getString(SPTools.userId); //此逻辑是为了兼容线上版本，1.0版本没有添加登录获取userId 逻辑

                                        if (StringUtils.isEmpty(userId)) { //如果userId 是null,通过接口获取到userId 后再执行对比逻辑
                                            getUserInfo(new ResultCallback() {
                                                @Override
                                                public void result(Object object) {
                                                    if (Boolean.parseBoolean(object.toString())) {
                                                        String userId = SPStaticUtils.getString(SPTools.userId);
                                                        if (!StringUtils.isEmpty(lat) && !StringUtils.isEmpty(lng) && !deviceUserId.equals(userId)) {
                                                            LatLng latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
                                                            latLngs.add(latLng);
                                                            nameList.add(name + "");
                                                        }
                                                    }
                                                }
                                            });
                                        }

                                        if (!StringUtils.isEmpty(lat) && !StringUtils.isEmpty(lng) && !deviceUserId.equals(userId)) {
                                            LatLng latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
                                            latLngs.add(latLng);
                                            nameList.add(name);
                                        }

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                for (int i = 0; i < latLngs.size(); i++) {
//                                    BitmapDescriptorFactory.fromResource(R.mipmap.icon_patrol_mark_znsb)
                                    String name = nameList.get(i);
                                    View view = View.inflate(context, R.layout.bubble_view, null);
                                    TextView textView = ((TextView) view.findViewById(R.id.title));
                                    textView.setText(name);
                                    MarkerOptions markerOptions = new MarkerOptions()
                                            .position(latLngs.get(i))
                                            .infoWindowEnable(false)
                                            .zIndex(MAP_INDEX)
                                            .icon(BitmapDescriptorFactory.fromView(view));
                                    Marker marker = aMap.addMarker(markerOptions);
                                    deviceMarker.add(marker);
                                }

                                if (latLngs.size() > 0 && deviceMarker == null) {
                                    aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(latLngs), MAP_FACTORY_PADDING));
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }


    /**
     * 获取用户信息
     */
    private void getUserInfo(ResultCallback resultCallback) {

        OkGo.<String>get(Constant.getInstance().GET_USER_INFO)
                .tag(this)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                UserInfoBean userInfoBean = new UserInfoBean();
                                userInfoBean = gson.fromJson(result, UserInfoBean.class);

                                UserInfoBean.UserBean userBean = userInfoBean.getUser();
                                String userId = userBean.getUserId();

                                if (!StringUtils.isEmpty(userId)) {
                                    SPStaticUtils.put(SPTools.userId, userId);//保存userId
                                    resultCallback.result(true);
                                } else {
                                    resultCallback.result(false);
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                    }
                });


    }
}